#!/usr/bin/env python

"""
bdf2inc.py - tool for converting BDF files into a format accepted by
aki-ledsuite

Copyright (C) 2009 Free Software Initiative of Japan

Written by Wiktor Langowski <jolkaczad@gmail.com>

Distributed under GNU General Public License version 3 (or later)

This script utilises the BDFlib library available at
http://gitorious.org/bdflib
"""

import sys
from bdflib import reader

if (len(sys.argv) == 1):
  print "error: A file name must be specified"
  exit (1)

f = open (sys.argv[1], 'r')
file_str = f.read()
llist = file_str.splitlines()

itl = iter(llist)

font = reader.read_bdf (itl)

"""
character range
"""
print "#define MIN_CHAR 0x"+ font.glyphs[0].name.lstrip('0')
print "#define MAX_CHAR 0x"+ font.glyphs[len(font.glyphs)-1].name.lstrip('0')

"""
font and segment widths
"""
max_width = 0
for g in font.glyphs:
  if (g.bbW > max_width):
    max_width = g.bbW

print "\n#define FIX_WIDTH " + str(max_width)
print "#define SEGM_SIZE (FIX_WIDTH*2+1)"

"""
the data
"""
print "\n"
print "static PROGMEM"
print "const unsigned char etl_font_data[] = {"

for g in font.glyphs:
  glist = g.data
  print "\t" + str(g.bbW) + ","
 
  nlist = [0] * 16
  for i in range (g.bbW):
    for j in range (len (glist)):
      k = i*2
      if (j >= 8):
	k += j/8

      nlist[k] += (glist[j] % 2) * pow(2, 7 - (j % 8))
      glist[j] /= 2

  nlist.reverse()
  for n in range (0, (len (nlist)) - 1, 2):
    print "\t" + str (nlist[n+1]) + ", " + str (nlist[n]) + ", "
    n += 1

print "};"
f.close ()
